package com.example.rice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.rice.common.CustomException;
import com.example.rice.common.R;
import com.example.rice.dto.DishDto;
import com.example.rice.dto.SetmealDto;
import com.example.rice.entity.Category;
import com.example.rice.entity.Dish;
import com.example.rice.entity.Employee;
import com.example.rice.entity.Setmeal;
import com.example.rice.service.CategoryService;
import com.example.rice.service.SetmealDishService;
import com.example.rice.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 套餐管理控制器
 */
@Slf4j
@RestController
@RequestMapping("setmeal")
public class SetmealController {

    //导入套餐类service层方法
    @Autowired
    private SetmealService setmealService;
    //导入套餐关系类service层方法
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增套餐接口，需要实现双存双删
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache" ,allEntries = true) //删除缓存中所有数据
    public R<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 分页查询套餐页面信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //构造分页构造器
        Page pageInfo = new Page<>(page,pageSize);
        //转化成DTO
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //进行查询
        setmealService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item->{
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null){
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        })).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }


    /**
     * 删除套餐信息
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache" ,allEntries = true) //删除缓存中所有数据
    public R<String> delete(@RequestParam List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * 更改菜品出售状态接口
     * @param
     * @return
     */
    @PostMapping ("/status/{state}")
    public R<String> updateStatus(@PathVariable int state,@RequestParam List<Long> ids){
        int count = 0;
        //统计一下选择的套餐是否全部处于需要更改状态
        for (Long i:ids) {
            Setmeal setmeal = setmealService.getById(i);
            if (setmeal.getStatus()==state){
                count++;
            }
        }
        //如果是更改状态直接抛出业务异常，提示用户无需更改
        if(count == ids.size()){
            if (state == 1){
                throw new CustomException("您选择的套餐已经全部处于启售状态无需更改！");
            }else {
                throw new CustomException("您选择的套餐已经全部处于停售状态无需更改！");
            }
        }
        for (Long i:ids) {
            Setmeal setmeal = setmealService.getById(i);
            setmeal.setStatus(state);
            setmealService.updateById(setmeal);
        }
        return R.success("更改成功");
    }


    /**
     * 根据id查询套餐信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<SetmealDto> getOne(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改前端传回来的工具类修改所有套餐相关信息
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success("修改菜品成功！");
    }

    /**
     * 根据条件查询套餐数据
     * setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getCreateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

}
